const { submitEvaluate, orderGoods } = require('../../api/order')
const { API_OK } = require('../../utils/setting')

Page({
  data: {
    list: [],
    star: 0,
    evaluate: ''
  },
  pageData: {
    submit: false,
    orderId: null
  },
  onLoad(options) {
    this.pageData.orderId = options.id
    this.getOrderGoods()
  },
  /**
   * 设置评价内容
   */
  handleChange(e) {
    console.log(e)
    this.data.list[e.target.dataset.index].content = e.detail.value.trim()
    this.setData({ list: this.data.list })
  },
  /**
   * 设置评分
   */
  chooseStarCount({ currentTarget }) {
    // console.log(currentTarget)
    const {index, key} = currentTarget.dataset
    this.data.list[index].score = key + 1
    this.setData({ list: this.data.list })
  },
  /**
   * 获取需要评价的商品
   */
  async getOrderGoods() {
    try {
      wx.showLoading({ title: '拼命加载中', mask: true })
      const res = await orderGoods({
        data: { order_id: this.pageData.orderId },
        callback: wx.hideLoading
      })
      // console.log(res)
      if (res.code === API_OK) {
        this.setData({
          list: res.data.goodsList.map(item => {
            return {
              goodsImage: item.image && item.image.file_path,
              goods_id: item.goods_id,
              order_goods_id: item.order_goods_id,
              score: 0,
              content: ''
            }
          })
        })
      } else {
        wx.showToast({ title: res.msg, duration: 1500, icon: 'none' })
      }
    } catch(err) {
      console.warn(err)
      wx.hideLoading()
    }
  },
  /**
   * 校验
   */
  validate() {
    for (let i = 0; i < this.data.list.length; i++) {
      if (this.data.list[i].score <= 0){
        wx.showToast({ title: '请设置评分', duration: 1500, icon: 'none' })
        return false
      }
      if (!this.data.list[i].content.trim()) {
        wx.showToast({ title: '请填写商品评价', duration: 1500, icon: 'none' })
        return false
      }
    }
    return true
  },
  /**
   * 提交评价
   */
  async submit() {
    if (this.pageData.submit) return
    if (!this.validate()) return
    this.pageData.submit = true
    try {
      wx.showLoading({ title: '正在提交', mask: true })
      const res = await submitEvaluate({
        data: {
          order_id: this.pageData.orderId,
          formData: JSON.stringify(this.data.list)
        },
        callback: wx.hideLoading
      })
      // console.log(res)
      this.pageData.submit = false
      if (res.code === API_OK) {
        wx.showToast({ title: '提交成功', icon: 'success', mask: true, duration: 1500 })
        setTimeout(() => {
          wx.navigateBack({ delta: 2 })
        }, 1500)
      } else {
        wx.showToast({ title: res.msg, duration: 1500, icon: 'none' })
      }
    } catch(err) {
      console.warn(err)
      this.pageData.submit = false
      wx.hideLoading()
    }
  }
})
